package com.bsoft.service.impl;

import com.bsoft.mapper.lis.HivPushMapper;
import com.bsoft.service.HivPushService;
import com.bsoft.utils.ConmonUtil;
import com.bsoft.utils.HttpClientUtil;
import com.bsoft.utils.JSONUtil;
import com.bsoft.utils.MD5Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 挂号实现类
 *
 * @author liujx
 * @date 2019/7/2
 */
@Service
@EnableTransactionManagement
public class HivPushServiceImpl extends ConmonUtil implements HivPushService {

    private static Logger logger = LoggerFactory.getLogger(HivPushServiceImpl.class);

    @Resource
    private HivPushMapper hivPushMapper;

    @Value("${hiv_login_username}")
    private String hiv_login_username;

    @Value("${hiv_login_password}")
    private String hiv_login_password;
    @Value("${hie_app_key}")
    private String hie_app_key;
    @Value("${secretKey}")
    private String secretKey;

    /*正式环境*/
    @Override
    public void hivPush_ProvincePt() throws Exception {

       /* //为接口的授权ID（需要管理员授权后 在集成平台Web端 API管理-》API详情-》API文档中获取）等待授权
        String hie_app_key = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJznXiiKhpfEH9v%2FnwLfxjhoUj2p4%2BwPDvxdgP03g4y9rxZ%2B84k%2FhVV8Oqs4zaZFyQUQVt6W6X5upGMT6RC%2BiHECAwEAAQ%3D%3D";
        //秘钥字符串=HIE_ADAPTER_382d8d3b4e6bc62de8b984ac84acf492
        String secretKey = "HIE_ADAPTER_382d8d3b4e6bc62de8b984ac84acf492";*/

        List<Map<String, Object>> hivList = hivPushMapper.getHIV_PushList();

        for (Map<String, Object> hivmap : hivList) {
            try {
                //接口的唯一ID（在集成平台Web端 API管理-》API详情-》API文档中获取
                String hie_event_code = "177cf201a6997f4ca0b8da298e31e3f1";
                //传当前时间戳 （时间戳必须为当前时间，精确到ms）
                long hie_time_stamp = System.currentTimeMillis();
                //为前三项和秘钥字符串的MD5值（32位小写）hie_secret=MD5(hie_event_code+hie_app_key+hie_time_stamp+秘钥字符串)（直接拼在一起，不要使用+号）
                String hie_secret = MD5Util.getMD5(hie_event_code + hie_app_key + hie_time_stamp + secretKey);

                String hiv_url_login = "https://integration.scwjxx.cn/adapter/http/ehrc/login/integration?"
                        + "hie_event_code=" + hie_event_code + "&hie_app_key=" + hie_app_key + "&hie_time_stamp=" + hie_time_stamp + "&hie_secret=" + hie_secret;

                String parm_login = "{\"username\":\"" + hiv_login_username + "\",\"password\":\"" + hiv_login_password + "\"}";
                String res = "";
                //获取token
                String loginToken = "";
                logger.error("HIV登录地址::"+hiv_url_login+"::入参"+parm_login);
                res = HttpClientUtil.doPostJsonHIV(hiv_url_login, parm_login, "", "");
                logger.info("HIV登录返回[" + hivmap.get("DOCTADVISENO") + "]::"+ res);
                Map<String, Object> loginResMap = JSONUtil.toHashMap(res);
                if ("200.0".equals(loginResMap.get("code").toString())) {
                    loginToken = ((Map<String, Object>) loginResMap.get("data")).get("token").toString();
                }else {
                    continue;
                }

                String hie_event_code_push = "301325e887294c91b96ee858d74abe88";
                long hie_time_stamp_push = System.currentTimeMillis();
                String hie_secret_push = MD5Util.getMD5(hie_event_code_push + hie_app_key + hie_time_stamp_push + secretKey);

                String hiv_url_push = "https://integration.scwjxx.cn/adapter/http/ehrchiv/v1.0/api/hiv/record/create?"
                        + "hie_event_code=" + hie_event_code_push + "&hie_app_key=" + hie_app_key + "&hie_time_stamp=" + hie_time_stamp_push + "&hie_secret=" + hie_secret_push;

                String parmHIVJson = JSONUtil.map2Json(hivmap);
                logger.error("HIV上传地址::"+hiv_url_push);
                logger.error("HIV上传入参::"+parmHIVJson);
                //获取token后再组装HIV上传数据
                String res_push = HttpClientUtil.doPostJsonHIV(hiv_url_push, parmHIVJson, "", loginToken);
                logger.error("HIV上传出参"+res_push);
                Map<String, Object> resmap = JSONUtil.toHashMap(res_push);
                if ("200.0".equals(resmap.get("code").toString())) {
                    hivmap.put("HIV_SC_TEXT",res_push.length()>1000?res_push.substring(0,1000):res_push);
                    hivPushMapper.updateJYTMXX(hivmap);
                }else if("500.0".equals(resmap.get("code").toString())){
                    hivmap.put("HIV_SC_TEXT",res_push.length()>1000?res_push.substring(0,1000):res_push);
                    hivPushMapper.updateJYTMXX_YC(hivmap);
                }else {
                    continue;
                }
            } catch (Exception e) {
                logger.error("循环上传HIV数据中有数据异常["+hivmap.get("DOCTADVISENO")+"]:",e);
            }

        }
    }


    /**
     * 手动编写事务代码如下：
     * 注意使用事务一定要是public的方法
     *
     * @return 是否执行成功
     */
    /*@Override
    @Transactional(rollbackFor = Exception.class)
    public String updateBRDA(Map<String, Object> req) {
        // 尽量要把select放到事务外面，因为查询不牵扯到事务
        List<Map<String, Object>> brdaInfoList = registerMapper.getBrdaList(req);

        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        // 定义该事务的名称、事务级别
        def.setName("upDaTransaction");
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        // 记录事务执行之前的状态
        TransactionStatus status = regTransactionManager.getTransaction(def);
        // 此处设定的是sql语句出错，所以使用try catch包围，也可以根据实际的业务确定执行还是回滚
        try {
            // 执行操作
            brdaInfoList.get(0).put("phoneNum",req.get("phoneNum"));
            int a = registerMapper.updateBrda(brdaInfoList.get(0));
            // 如果没有出错，提交该事务
            regTransactionManager.commit(status);
        } catch (Exception e) {
            // 错误输入改成日志
            System.err.println(e.getMessage());
            // 如果发送错误回滚该事物
            regTransactionManager.rollback(status);
            return getSuccessFull("更新档案("+brdaInfoList.get(0).get("BRID")+")失败!!");
        }
        return getSuccess("更新成功!!");
    }*/
   /* @Override
    @Transactional(rollbackFor = Exception.class)
    public String updateBRDA(Map<String, Object> req) {
        int a = registerMapper.updateBrda(req);
        if (a == 0) {
            throw new CommonException("更新失败!");
        }

        TransactionSynchronizationManager.bindResource("req", req);
        // 在事务提交后发送邮件
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCommit() {
                Map<String, Object> aa = (Map<String, Object>) TransactionSynchronizationManager.getResource("req");
                aa.put("phoneNum","aaa");
                aa.put("patientId","11");
                String s1 = JSONUtil.map2Json(aa);
                String s = HttpClientUtil.doPostJson("http://127.0.0.1:8089/bsoft/register/patientIsMatch", s1);
                System.out.println("返回结果::"+s);
            }
        });


        if (1!=0){
            throw new CommonException("更新失败!");
        }

        return getSuccess("更新成功!!");
    }*/


}
